package converter;

import exception.TypeConversionException;
import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;

import static content.common.ExceptionMessage.PARAMS_ENUM_NOT_MATCH;

/**
 * integer类型转化成enum
 * @param <T>
 */
public class IntegerToEnumConverter<T extends IntegerBaseEnum> implements Converter<Integer, T> {

    private HashMap<Integer, T> enumMap = new HashMap<>();

    public IntegerToEnumConverter(Class<T> enumType) {
        T[] constants = enumType.getEnumConstants();
        for (T constant : constants) {
            enumMap.put(constant.getCode(), constant);
        }
    }

    @Override
    public T convert(Integer source) {
        T t = enumMap.get(source);
        if (t == null) {
            throw new TypeConversionException(PARAMS_ENUM_NOT_MATCH);
        }
        return t;
    }
}
